package com.wenx.v3auth.controller;

import com.wenx.v3auth.service.V3TokenRefreshService;
import com.wenx.v3core.response.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 令牌管理控制器
 * 提供令牌缓存管理和监控接口
 */
@Slf4j
@RestController
@RequestMapping("/admin/token")
@RequiredArgsConstructor
@Tag(name = "令牌管理", description = "OAuth2令牌缓存管理和监控接口")
public class TokenManagementController {

    private final V3TokenRefreshService tokenRefreshService;

    /**
     * 获取缓存统计信息
     */
    @GetMapping("/statistics")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(
        summary = "获取令牌缓存统计信息",
        description = "获取系统中令牌缓存的详细统计信息，包括各类令牌数量、数据库授权数量等。需要管理员权限。",
        security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "成功获取缓存统计信息",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = R.class)
            )
        ),
        @ApiResponse(responseCode = "401", description = "未授权访问"),
        @ApiResponse(responseCode = "403", description = "权限不足，需要管理员权限"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R getCacheStatistics() {
        try {
            V3TokenRefreshService.CacheStatistics stats = tokenRefreshService.getCacheStatistics();
            return R.ok(stats);
        } catch (Exception e) {
            log.error("获取缓存统计信息失败", e);
            return R.failed("获取缓存统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发缓存清理
     */
    @PostMapping("/cleanup")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(
        summary = "手动触发缓存清理",
        description = "手动触发令牌缓存清理操作，清理过期的令牌和授权信息。需要管理员权限。",
        security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "缓存清理操作成功",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = R.class)
            )
        ),
        @ApiResponse(responseCode = "401", description = "未授权访问"),
        @ApiResponse(responseCode = "403", description = "权限不足，需要管理员权限"),
        @ApiResponse(responseCode = "500", description = "缓存清理操作失败")
    })
    public R manualCleanup() {
        try {
            tokenRefreshService.manualCleanupCache();
            return R.ok("缓存清理操作已完成",null);
        } catch (Exception e) {
            log.error("手动缓存清理失败", e);
            return R.failed("缓存清理操作失败:"+e.getMessage(),null);
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    @Operation(
        summary = "令牌服务健康检查",
        description = "检查令牌服务的健康状态，包括缓存状态和服务可用性"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "健康检查完成",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = R.class)
            )
        ),
        @ApiResponse(responseCode = "500", description = "服务不健康")
    })
    public R healthCheck() {
        try {
            V3TokenRefreshService.CacheStatistics stats = tokenRefreshService.getCacheStatistics();
            return R.ok(Map.of(
                "status", "healthy",
                "cached_authorizations", stats.getCachedAuthorizations(),
                "cached_token_mappings", stats.getCachedTokenMappings(),
                "database_authorizations", stats.getDatabaseAuthorizations(),
                "active_tokens", stats.getActiveTokens(),
                "last_cleanup_time", stats.getLastCleanupTime()
            ));
        } catch (Exception e) {
            log.error("健康检查失败", e);
            return R.failed(Map.of(
                "status", "unhealthy",
                "error", e.getMessage()
            ));
        }
    }
} 